import { setItem } from '@/utils/storage'
import { defineStore } from 'pinia'

export const websocketStore = defineStore('websocketStore', {
  state: () => {
    return {
      ws: JSON.parse(sessionStorage.getItem('websocketClient')) as WebSocket || null,
      websocketClientIp: localStorage.getItem('websocketClientIp') || '127.0.0.1',
      websocketClientPort: parseInt(localStorage.getItem('websocketClientPort')) || null,
      websocketClientPath: localStorage.getItem('websocketClientPath') || '/',
      websocketServerPath: localStorage.getItem('websocketServerPath') || '/',
      websocketServerPort: parseInt(localStorage.getItem('websocketServerPort')) || null,
      websocketClientStatus: localStorage.getItem('websocketClientStatus') === 'true',
      websocketServerStatus: localStorage.getItem('websocketServerStatus') === 'true',
      websocketLog: JSON.parse(sessionStorage.getItem('websocketLog')) as Array<String> || [] as Array<String>
    }
  },
  actions: {
    setWS (payLoad:WebSocket) {
      this.ws = payLoad
      sessionStorage.setItem('websocketClient', JSON.stringify(this.ws))
    },
    setWebsocketLog (payLoad:string) {
      if (this.websocketLog.length >= 200) {
        this.websocketLog.shift()
      }
      this.websocketLog.push(payLoad)
      sessionStorage.setItem('websocketLog', JSON.stringify(this.websocketLog))
    },
    setWebsocketClientStatus (payLoad:boolean) {
      this.websocketClientStatus = payLoad
      setItem('websocketClientStatus', JSON.stringify(payLoad))
    },
    setWebsocketServerStatus (payLoad:boolean) {
      this.websocketServerStatus = payLoad
      setItem('websocketServerStatus', JSON.stringify(payLoad))
    },
    setWebsocketClientIp (payLoad:string) {
      this.websocketClientIp = payLoad
      setItem('websocketClientIp', payLoad)
    },
    setWebsocketClientPort (payLoad:number) {
      this.websocketClientPort = payLoad
      setItem('websocketClientPort', JSON.stringify(payLoad))
    },
    setWebsocketServerPort (payLoad:number) {
      this.websocketServerPort = payLoad
      setItem('websocketServerPort', JSON.stringify(payLoad))
    },
    setWebsocketServerPath (payLoad:string) {
      this.websocketServerPath = payLoad
      setItem('websocketServerPath', payLoad)
    },
    setWebsocketClientPath (payLoad:string) {
      this.websocketClientPath = payLoad
      setItem('websocketClientPath', payLoad)
    }
  }
})
